﻿using System;
using System.Linq;
using System.Web.Mvc;
using WeBlog.Interfaces;
using WeBlog.Models;
using WeBlog.Repositories;
using WeBlog.Services;

namespace WeBlog.Controllers {    
	public class CommentController : ApplicationController
	{        
		private readonly IEmailService _emailService;

		public CommentController(IUnitOfWork unitOfWork, IEmailService emailService )
			: base( unitOfWork)
		{
			_emailService = emailService;
		}

        [WeBlogAuthorize(Role.Admin), Theme("Admin")]
		public ActionResult Manage( GridSettings settings )
		{
			var model = new ManageCommentsViewModel(UnitOfWork, settings);
			UpdateModel(model);
            return View(model);
		}

		[HttpPost, WeBlogAuthorize(Role.Admin)]
		public JsonResult UpdateStatus(int[] keys, int status)
		{
			try
			{
				var repository = new CommentRepository(UnitOfWork);
				foreach (int value in keys) {
					PostComment comment = repository.FindById(value);
					comment.CommentStatus = (CommentStatus)status;
				}
				UnitOfWork.Commit();
				return Json(new JsonResponse { Success = true });
			}
			catch (Exception ex) {
				return Json(new JsonResponse { Success = false, Message = ex.Message });
			}
		}

		[HttpPost, WeBlogAuthorize(Role.Admin)]
		public JsonResult Approve(int commentId)
		{
			try
			{
				var repository = new CommentRepository(UnitOfWork);
				PostComment comment = repository.FindById(commentId);
				comment.CommentStatus = CommentStatuses.Approved;
				UnitOfWork.Commit();
				return Json(new JsonResponse { Success = true });
			}
			catch (Exception ex)
			{
				return Json(new JsonResponse { Success = false, Message = ex.Message });
			}
		}

		[HttpPost, WeBlogAuthorize(Role.Admin)]
		public JsonResult Delete(int commentId)
		{
			try 
			{
				var repository = new CommentRepository(UnitOfWork);
				PostComment comment = repository.FindById(commentId);
				repository.Remove(comment);
				UnitOfWork.Commit();
				return Json(new JsonResponse { Success = true });
			}
			catch (Exception ex) {
				return Json(new JsonResponse { Success = false, Message = ex.Message });
			}
		}

		public JsonResult Flag(int commentId)
		{
			var repository = new CommentRepository(UnitOfWork);
			PostComment comment = repository.FindById(commentId);		        

			// Notify admins            
			_emailService.SendCommentFlagged(comment);

			return Json(new JsonResponse
			{
				Success = true,
				Message = Resources.Strings.Comment_FlaggedMessage
			});
		}        
	}
}
